import os

from win32com import client as wc
from time import sleep


def convert_doc_to_docx_and_pdf(doc_path, output_dir):
    """将单个DOC文件转换为DOCX和PDF"""
    word = wc.Dispatch("KWPS.Application")
    word.Visible = False
    try:
        doc_name = os.path.splitext(os.path.basename(doc_path))[0]
        # docx_path = os.path.join(output_dir, f"{doc_name}.docx")
        pdf_path = os.path.join(output_dir, f"{doc_name}.pdf")

        doc = word.Documents.Open(doc_path)

        # # 保存为DOCX
        # doc.SaveAs(docx_path, FileFormat=16)
        # print(f"转换成功: {doc_path} -> {docx_path}")

        # 保存为PDF
        doc.SaveAs(pdf_path, FileFormat=17)
        print(f"转换成功: {doc_path} -> {pdf_path}")
        return True
    except Exception as e:
        print(f"转换失败 {doc_path}: {e}")
        return False
    finally:
        print('finally')
        doc.Close()
        word.Quit()


def process_folder(folder_path, output_base_dir):
    for root, dirs, files in os.walk(folder_path):
        # 为当前文件夹创建对应的输出目录
        relative_path = os.path.relpath(root, folder_path)
        output_dir = os.path.join(output_base_dir, relative_path)
        os.makedirs(output_dir, exist_ok=True)
        print(f"正在处理文件夹: {files}")
        for file in files:
            if file.lower().endswith('.doc'):
                doc_path = os.path.join(root, file)

                # 转换文件
                if convert_doc_to_docx_and_pdf(doc_path, output_dir):
                    # sleep(3)
                    try:
                        # 删除原始DOC文件
                        os.remove(doc_path)
                        print(f"已删除原始文件: {doc_path}")
                    except Exception as e:
                        print(f"删除文件失败 {doc_path}: {e}")

def work():
    input_doc = "C:\\fileDir\\"
    output_dir = "C:\\fileDir\\"
    while True:
        try:
            import pythoncom  # 确保导入pythoncom
            pythoncom.CoInitialize()
            import converDoc  # 确保导入converDoc
            converDoc.process_folder(input_doc, output_dir)
            pythoncom.CoUninitialize()
            # 检查是否还有 .doc 文件
            has_doc_files = False
            for root, dirs, files in os.walk(input_doc):
                for file in files:
                    if file.lower().endswith('.doc'):
                        has_doc_files = True
                        break
                if has_doc_files:
                    break
            if not has_doc_files:
                break  # 没有 .doc 文件了，退出循环
        except Exception as e:
            print(f"运行出错，正在重启: {e}")